<template>
  <Select :multiple="multiple" :disabled="disabled" :value="value" :datas="data" @change="change" @input="input">
    <template slot="top">
      <h-search @search="search" @input="searchInput" block v-model="filter" :height="28"></h-search>
    </template>
    <template slot="bottom" @mousedown.stop.prevent>
      <Button icon="h-icon-left" :no-border="true" @click="up"></Button>
      <span class="gray-color">{{page}}</span>
      <Button icon="h-icon-right" :no-border="true" @click="down"></Button>
    </template>
  </Select>
</template>
<script>
export default {
  props: {
    multiple: {
      default: false,
    },
    disabled: {
      default: false,
    },
    value: "",
    url: "",
    of: {},
  },
  computed: {
    action() {
      return this.$store.state.forms.action;
    },
  },
  mounted() {
    if (!!this.value) {
      if (this.value.indexOf(",") != -1) {
        this.value = this.value.split(",");
      }
      if (this.multiple && data instanceof Array) {
        this.selected = this.value;
      } else {
        this.selected = [this.value];
      }
    }
    if (this.action != "edit" && this.action != "see") {
      this.loadData();
    }
  },
  watch: {
    of(val) {
      this.selected = [];
      this.filter = "";
      this.initFlag = false;
      this.loadData();
    },
    value(data) {
      if (!!data) {
        if (data.indexOf(",") != -1) {
          data = data.split(",");
        }
        if (this.multiple && data instanceof Array) {
          this.selected = data;
        } else {
          this.selected = [this.value];
        }
        if (this.initFlag) {
          this.initFlag = false;
          this.loadData();
        }
      }
    },
  },
  data() {
    return {
      initFlag: true,
      page: 1,
      size: 10,
      data: [],
      selected: [],
      filter: "",
    };
  },

  methods: {
    searchInput(data) {
      if (data.length < 1) {
        return;
      }
      this.search(data);
    },
    search(data) {
      this.current = 1;
      this.loadData();
    },
    input(data) {
      this.selected = [];
      if (!!this.multiple && data instanceof Array) {
        this.selected = data;
      }
      this.$emit("input", data);
    },
    change(data) {
      this.$emit("change", data);
    },
    loadData() {
      let params = {
        page: {
          current: this.page,
          size: this.size,
        },
        filter: this.filter,
        of: this.of,
        selected: this.selected,
      };
      this.$axios.post(this.url, params).then((res) => {
        let data = res.data.data;
        if (!data) {
          return;
        }
        this.data = data.rows;
      });
    },
    up() {
      if (this.page > 1) {
        this.page--;
        this.loadData();
      }
    },
    down() {
      this.page++;
      this.loadData();
    },
  },
};
</script>